/**
 *  Zing News Code
 *  Version 2.87 (08/05/2014)
 */

// check if it's correct domain
var isEmbed = (window !== window.parent), Player;

if ((typeof debug_mode === "undefined") && (window.location.hostname.indexOf('localhost') < 0) && (window.location.hash.search(/singleplayer|redirected/ig)<0) && (isEmbed || window.top.location.hostname.indexOf('news.zing.vn') < 0)) {
    var origin = window.location.pathname;
    if (DEVICE.type === 'desktop') {
        window.top.location.href = 'http://news.zing.vn/' + origin + '#redirected';
    }
}

$.ajaxSetup({
    timeout: 5000
});

// initial configuration
var APP_ID = '622829237762080';
var INITIAL_TIME = now();
var page = new Page();
if (!$.support.transition) $.fn.transition = $.fn.animate;

$(document).ready(function () {
    if ($.cookie) {
        $.cookie.json = true;
    }

    if ($(document).width() > 1200) {
        DEVICE.screen = "wide";
    } else {
        DEVICE.screen = "standard";
    }

    page.init();

    // check if version cookie set, if yes, extend it for another day
    var cookieMobile = $.cookie('znews_mobile');
    if (cookieMobile != null) {
        $.cookie('znews_mobile', cookieMobile, {
            expires: 1,
            path: '/'
        });
    }

    /*
    if (page.getPageType() == 'home') {
        midPageDetector.attach();
    }
    */

});

$(window).bind('load', function () {
    page.setupScrollbar('.scroll');
    page.slider.init();
    page.ticker.init();

    if (page.getPageType()=='article') {
        var tracker = page.storage.load('history');
        if(tracker==null || tracker===false) {tracker = "";}
        if (tracker.search(page.article.getArticleId())<0) {
            tracker += page.article.getArticleId()+',';
            page.storage.insert('history',tracker);
        }
    }


    if (window.location.hash.search('app')<0) {
        if(DEVICE.platform=='ios') {
            announce(
                'app_announce',
                'CẬP NHẬT: App Zing.vn trên iPhone/iPad đã được cập nhật phiên bản mới ổn định hơn và hỗ trợ bài video. Tải và trải nghiệm ngay!',
                'https://itunes.apple.com/vn/app/zing.vn/id818187465?mt=8',
                {
                    platform:'ios'
                }
            );
        }
        else if (DEVICE.platform == 'android') {
            announce(
                'app_announce',
                'THÔNG BÁO: Zing.vn ra mắt phiên bản app Zing 2.0 dành cho thiết bị Android đẹp và tiện lợi hơn. TẢI NGAY!',
                'market://details?id=com.zing.znews',
                {
                    platform:'android'
                }
            );
        }
    }

}).on('blur', function () {
    INITIAL_TIME = now();
});

/**
 * Check if user comeback after certain amount of time then reload the content
 */
if (page.getPageType() == 'home') {
    $(window).on('focus', function () {
        var time = Math.floor(( now() - INITIAL_TIME) / 60000);
        //ga('send', 'event', 'Window', 'Refocus Interval',window.location.pathname, time);
        if (time >= 15) {
            //ga('send', 'event', 'Window', 'Auto Reloading', window.location.pathname, time);
            window.location.reload(true);
        }
    });
}

function Page() {
    var self = this;
    var cachedPageType;


    this.livestream = new LiveStream();
    //this.interview = new Interview();
    this.ticker = null;
    this.slider = new Slideshow('section.pictures', 'article');
    this.article = new Article();
    this.socialplugin = new SocialPlugin();
    this.storage = new Storage('local');
    this.navigationMenu;

    this.init = function () {

        Player = new VideoPlayer().init();
        self.setupTrackingLink();
        self.ticker = new NewsTicker($('.hotnews'), 'li');
        self.renderSocialCount();



        self.setupSearchBox();
        self.article.init();

        self.navigationMenu = new NavigationMenu();
        self.navigationMenu.show();

        self.setupToolbox();
        self.socialplugin.init();

        $('#top .parent').hover(function () {
            $(this).addClass('active');
        }, function () {
            $(this).removeClass('active');
        });

        // render article publish time
        var $timers = $('time');
        for (var i = 0, length = $timers.length; i < length; i++) {
            var $timer = $timers.eq(i),
                friendly = $timer.html() + page.formatTime($timer.attr('datetime'), {
                    friendly: $timer.hasClass('friendly')
                });

            $timer.html(friendly);
        };

        // initialize grid layout
        var $gridView = $('.gridview');
        if ($gridView.length > 0 && DEVICE.type == "desktop") {
            loadPlugin('isotope', 'isotope.1.5.25.js', function(){
                $gridView.isotope({
                    // options
                    itemSelector: 'article',
                    layoutMode: 'masonry',
                    transformsEnabled: false,
                    gutterWidth: 20
                });
            });

        }

        // setup category feed subscription dropdown box on homepage
        $('section.category .followbox').hover(
            function () {
                $(this).addClass('hovering');
            },
            function () {
                $(this).removeClass('hovering');
            }
        );

        // initialize live stream
        if ($('#livestream').length > 0 && $('#livestream .controller').length > 0) {
            page.livestream.init($('#livestream .controller').attr('data'));
        }

        // initialize live interview if status = live/question
        var $interviews = $('div[submit*="interview"]');
        $interviews.each(function(){
            (new Interview()).init(this,$(this).attr('data'),$(this).attr('submit'));
        });
        /*
        if ($('#interview').length > 0 && ($('#interview').hasClass('live') || $('#interview').hasClass('question'))) {
            $('#interview').each(function(){
                log($(this).attr('data'));
                log($(this).attr('submit'));
            });
            page.interview.init($('#interview').attr('data'), $('#interview').attr('submit'));
        }
        */

        // showing pr articles in category page
        var pageType = self.getPageType();
        if (pageType === 'category') {
            var target = '.cate_content section.cate_content';
            if ($(target).length==0) {
                target = 'section.cate_content';
            }
            var $adsArticles = $(target+' article.advertising');
            if ($adsArticles.length > 0) {
                $articles = $(target+' article:not(.advertising)');

                var adsIndex = 0,
                    adsLength = $adsArticles.length;

                for (var i = 0, length = $articles.length; i < length; i += 2) {
                    if (adsIndex >= adsLength) {
                        break;
                    }
                    $adsArticles.eq(adsIndex).insertAfter($articles.eq(i)).show();
                    ++adsIndex;
                }

                while (adsIndex < adsLength) {
                    $adsArticles.eq(adsIndex).insertAfter($(target+' article:last-of-type')).show();
                    ++adsIndex;
                }
            }
        }

        /* Banner ad */
        if (self.getPageType() == 'home') {                        
            //$('.sidebar>section.pictures').before('<a href="http://news.zing.vn/Chieu-75-phong-van-truc-tuyen-Minh-Thuy--Nhat-Thuy-post414114.html#banner" target="_blank" style="display:block; margin-bottom:10px;"><img src="http://stc.v3.news.zing.vn/images/minhthuynhatthuy300.jpg" /></a>');
        }


        return self;
    };



    // insert tracking code for links
    this.setupTrackingLink = function () {
        var $articles = $('article');
        for (var i = 0, length = $articles.length; i < length; i++) {
            var $article = $articles.eq(i);
            var target = generateLinkTrack($article);
            $article.find('> .cover a, > header h1 a').attr('href', target);
        };

        var $relates = $('article ul.relate a');
        for (var i = 0, length = $relates.length; i < length; i++) {
            var $relate = $relates.eq(i);
            $relate.attr('href', $relate.attr('href') + '#relate-article');
        };

        var $inners = $('.inner-article a');
        for (var i = 0, length = $inners.length; i < length; i++) {
            var $inner = $inners.eq(i);
            $inner.attr('href',$inner.attr('href')+'#inner-article');
        };
    };

    // render social counter for articles
    this.renderSocialCount = function () {
        var news = "",
            $hotArticle;
        var $socialCounters = $('.social.hot', 'article');

        for (var i = 0, j = $socialCounters.length; i < j; i++) {
            var $socialCounter = $socialCounters.eq(i);

            $socialCounter.show().on("mouseenter", function (e) {
                self.showHoverBox('<div class="content">Bài viết có nhiều phản hồi của bạn đọc</div>', {
                    'top': e.clientY + 15,
                    'left': e.clientX
                });
            }).on('mouseleave', function () {
                $('#popup').hide();
            });
            try {
                $hotArticle = $socialCounter.parents('article');
                var atitle = $hotArticle.find('> header h1 a').text();
                var aCover = $hotArticle.find('> .cover');
                var aTime = new Date($hotArticle.find('time').attr('datetime'));


                if ($(aCover).find('img').length > 0) {
                    aCover = $(aCover).find('img').attr('src');
                } else {
                    aCover = $(aCover).css('background-image').replace(/url\(|\)/gi, '');
                }
                if (news.search(atitle) < 0 && Math.floor((INITIAL_TIME - aTime.getTime()) / 86400000) == 0) {
                    news += '<li><a href="' + $hotArticle.find('> header h1 a').attr('href') + '"><span class="cover" style="background-image:url(' + aCover + ')"></span>' + atitle + '</a></li>';
                }
            } catch (e) {};
        };

        if ($socialCounters.length > 0) {
            $('body').append($('<div>', {
                'id': 'hotnews'
            }).html('<ul>' + news + '</ul'));

            var $hotnews = $('#hotnews');

            $('#zingheader .wrapper').append('<div id="noti5"><a href="#" class="btnHot">NÓNG 24h</a></div>');
            $('#noti5 .btnHot').append('<span>' + $hotnews.find('li').length + '</span>').on('click', function () {
                if ($hotnews.is(':visible')) {
                    $hotnews.hide();
                    $('body').unbind('click');
                } else {
                    $hotnews.show();
                    setTimeout(function () {
                        $('body').on('click', function () {
                            $hotnews.hide();
                        });
                    }, 200);
                }
                return false;
            });
        }

    };

    /**
     * Hovering box display at an exact coordinate on screen
     **/
    this.showHoverBox = function (content, position, styles, action) {
        var $popup = $('#popup');

        if ($popup.length == 0) {
            $('body').append($('<div>', {
                id: 'popup'
            }));

            $popup = $('#popup');
        }

        $popup.html(content);
        if (position) {
            $popup.css({
                top: position.top + 'px',
                left: position.left + 'px'
            });
        }

        if (action) {
            action();
        }

        if (styles) {
            $popup.css(styles);
        }

        $popup.show();

    };

    this.hideHoverBox = function () {
        var $popup = $('#popup');
        $popup.empty().hide();
        $popup.unbind();
    };

    /**
     * Top header banner to be displayed on mobile device
     */
    this.popupMobile = function () {
        if (DEVICE.type == "tablet" || DEVICE.type == "smartphone") {
            if ($.cookie('mobileOption') == null && $.cookie('znews_mobile') == null) {
                // if not set & not ask yet
                if (confirm("Bạn đang xem giao diện đầy đủ của Zing News. Tùy theo mạng hoặc cấu hình, trang có thể tải chậm. Bạn có muốn chuyển sang mobile?") == true) {
                    $.cookie('znews_mobile', 1, {
                        expires: 1,
                        path: '/'
                    });
                    $.cookie('mobileOption', 1, {
                        path: '/'
                    });
                    window.location.reload(true);
                } else {
                    $.cookie('mobileOption', 1, {
                        path: '/'
                    });
                }
            } else if ($.cookie('znews_mobile') != null) {
                // extend save option
                var value = $.cookie('znews_mobile');
                $.cookie('znews_mobile', value, {
                    expires: 1,
                    path: '/'
                });
            }
        }
    };

    // Setup Search box
    this.setupSearchBox = function () {
        var $searchBox = $('#searchbox'),
            $searchInput = $searchBox.find('input[type="text"]');

        $searchInput.focus(function () {
            if ($searchInput.val() == 'Nhập nội dung cần tìm...') {
                $searchInput.val('');
            }
        }).blur(function () {
            if ($.trim($searchInput.val()) == '') {
                $searchInput.val('Nhập nội dung cần tìm...');
            }
        });

        $searchBox.submit(function () {
            var url = window.location.origin,
                keyword = $.trim($searchInput.val());
            if (keyword != '' && keyword != 'Nhập nội dung cần tìm...') {
                keyword = keyword.replace(/\s+/, "-");
                url += "/tim-kiem/" + encodeURIComponent(keyword) + '.html';
            }
            window.location.href = url;
            return false;
        });
    };

    /*
    this.notification = function(icon, title, message, url) {
        var noti = $('#notification');
        if ($(noti).length == 0) {
            noti = $('<div>', {id:"notification"});
            $(noti).append('<a class="btnLink"><img src="" width="36" height="36" class="icon" /><h1></h1><p></p></a><a href="#close" class="btnClose">Đóng</a>');
            $('body').prepend(noti);
            $(noti).find('.btnClose').on('click', function(){
                $(noti).transition({
                    marginTop: '-56px'
                }, 200);
            });
        }

        $(noti).find('.btnLink').attr('href',url).attr('title', title);
        $(noti).find('img.icon').attr('src', icon);
        $(noti).find('h1').text(title);
        $(noti).find('p').text(message);
        $(noti).transition({ marginTop: '0px'}, 500);
    };
    */

    /**
     * Toolbox display utilities link on page, such as contact info
     */
    this.setupToolbox = function () {
        $toolbox = $('#toolbox');
        $btnToTop = $toolbox.find('li.toTop a');
        $btnEmail = $toolbox.find('li.email a');
        $btnPhone = $toolbox.find('li.phone a');

        $(window).bind('scrollstop', function () {
            var scrollTop = $(window).scrollTop();
            if (scrollTop > 200) {
                $btnToTop.stop().fadeIn();

                $('.btnToTop').css('display', 'block');

                if (scrollTop > 400 && page.article.getArticleType() != null && !$('#pushnotification').hasClass('hidden') && !$('#pushnotification').is(':visible')) {
                    if(!$('body').hasClass('appview')){page.showBottomBar();}
                }

                self.navigationMenu.show();
                self.navigationMenu.updateCurrent(scrollTop);
            } else {
                self.navigationMenu.hide();
                $btnToTop.stop().fadeOut();
                $('#pushnotification .actions .btnToTop').hide();
            }
        });
        $btnToTop.on('click', function () {
            self.scrollTo();
            return false;
        });
        $btnEmail.on('click', function () {
            showEmailBox();
            return false;
        });
        $btnPhone.on('click', function () {
            showPhoneBox();
            return false;
        });
    };

    /**
     * Hidden scrolling mechanism
     */
    this.setupScrollbar = function (scrollElement) {
        var $scrollElement = $(scrollElement);
        if ($scrollElement.length > 0 && DEVICE.type == "desktop") {
            $scrollElement.mCustomScrollbar({
                scrollButtons: {
                    enable: false
                },
                theme: "dark",
                autoHideScrollbar: true,
                autoDraggerLength: false
            });
        }
    };



    /**
     * Timestamp format utilities, able to convert to friendly format such as "2 hours ago"
     */
    this.formatTime = function (timestring, options) {
        //console.log(timestring);
        var difference, days, hours, minutes, month, prefix, date;

        if (parseInt(timestring)<10000) {
            date = new Date(timestring.replace(/-/g,'/').replace('+', ' +'));
        } else {
            date = new Date((parseInt(timestring)-25200)*1000);
        }

        prefix = options == null || options.prefix == null ? "" : options.prefix;

        if (options && options.friendly === true) {
            difference = now() - date.getTime();

            days = Math.floor(difference / 1000 / 60 / 60 / 24);
            difference -= days * 1000 * 60 * 60 * 24;
            hours = Math.floor(difference / 1000 / 60 / 60);
            difference -= hours * 1000 * 60 * 60;
            minutes = Math.floor(difference / 1000 / 60);
            difference -= minutes * 1000 * 60;

            //console.log('friendly:'+timestring);
            if (days == 0 && hours == 0) {
                return prefix + minutes + " phút trước";
            } else if (days == 1) {
                return prefix + "Hôm qua, lúc " + date.getHours() + " giờ " + date.getMinutes() + ' phút';
            }
        }

        hours = (date.getHours() < 10 ? '0' : '') + date.getHours();
        minutes = (date.getMinutes() < 10 ? '0' : '') + date.getMinutes();
        days = (date.getDate() < 10 ? '0' : '') + date.getDate();
        month = (date.getMonth() < 9 ? '0' : '') + (date.getMonth() + 1);

        return prefix + " " + hours + ":" + minutes + " ngày " + days + "/" + month + "/" + date.getFullYear();
    };

    /**
     * Bookmarking mechanism
     */
    this.addBookmark = function () {
        if (window.sidebar && window.sidebar.addPanel) { // Mozilla Firefox Bookmark
            window.sidebar.addPanel(document.title, window.location.href, '');
        } else if (window.external && ('AddFavorite' in window.external)) { // IE Favorite
            window.external.AddFavorite(location.href, document.title);
        } else if (window.opera && window.print) { // Opera Hotlist
            this.title = document.title;
            return true;
        } else { // webkit - safari/chrome
            if (DEVICE.browser=='chrome') {
                window.location.href="https://chrome.google.com/webstore/detail/zing-plus/jagbegdddghlidpmkamknochllodpdco?hl=vi";
            } else {
                alert('Vui lòng bấm tổ hợp phím ' + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 'Command/Cmd' : 'CTRL') + ' + D để lưu trang.');
            }

        }
    };

    /**
     * Provide mechanism to popup modal dialog requesting user input
     */
    this.showDialog = function (title, content, actions) {
        if (content == null) {
            return;
        }

        var $dialog = $('#dialog');

        if ($dialog.length == 0) {
            $('body').append($('<div>', {
                id: 'dialog'
            }));

            $dialog = $('#dialog');

            var dialogHtml = '<div>' +
                '<div class="header"></div>' +
                '<div class="content"></div>' +
                '<div class="action"><button class="btnSubmit">Đồng ý</button><button class="btnCancel">Đóng</button></div>' +
                '</div>';

            $dialog.html(dialogHtml);
        }

        var $btnSubmit = $dialog.find('.action button.btnSubmit'),
            $btnCancel = $dialog.find('.action button.btnCancel');

        $dialog.find('.header').html(title || 'Thông báo');
        $dialog.find('.content').html(content);

        $btnCancel.text('Đóng');

        if (actions != null) {
            if (actions.submit != null) {
                $btnSubmit.html(actions.submit.text || 'Đồng ý');

                $btnSubmit.on('click', function () {
                    actions.submit.action();
                }).show();
            } else {
                $btnSubmit.hide();
            }
            if (actions.cancel != null) {
                if (actions.cancel.text != null) {
                    $btnCancel.html(actions.cancel.text);
                }
            }
        }

        $btnCancel.on('click', function () {
            if (actions && actions.cancel && actions.cancel.action) {
                actions.cancel.action();
            }
            self.closeDialog();
        });

        $btnCancel.show();

        $dialog.find('> div').css({
            'margin-top': '-' + Math.round($('#dialog > div').height() / 2) + 'px'
        });

        $dialog.show();
    };

    this.closeDialog = function () {
        //console.log("close dialog");
        var $dialog = $('#dialog');
        $dialog.hide();
        $dialog.find('.header').empty();
        $dialog.find('.content').empty();
        $dialog.find('.action button').unbind('click').hide();
    };

    /**
     * Bottom bar display
     */
    this.showBottomBar = function () {
        if (DEVICE.screen != 'wide') {
            $('#pushnotification').css('bottom', '-50px');
            $('#pushnotification').show().transition({
                'bottom': '0px'
            });
        }

    };
    this.hideBottomBar = function () {
        if (DEVICE.screen == 'wide') {
            $('#pushnotification').hide();
        } else {
            $('#pushnotification').transition({
                'bottom': '-70px'
            }, 500, function () {
                $('#pushnotification').hide();
                $('#pushnotification').addClass('hidden');
            });

        }

    };

    /**
     * Provide mechanism to display small real time notification on the bottom right corner of the screen
     */
    this.pushNotification = function (content, action) {
        if ($('#popNotification').length == 0) {
            $('body').append($('<div>', {
                'id': 'popNotification'
            }).html('<div>'));
        }
        if (content == null) return;
        $('#popNotification > div').html(content);
        if (action) {
            $('#popNotification > div').bind('click', function () {
                action();
            });
        } else {
            $('#popNotification > div').bind('click', function () {
                self.hidePopNotification();
            });
        }
        $('#popNotification').fadeIn(500);
        /*
        $('#popNotification').show().transition({
            'right':'10px'
        });
        */
    };
    this.hidePushNotification = function () {
        /*
        $('#popNotification').transition({
            'right':'-160px'
        }, 500, function(){
            $('#popNotification > div').unbind().empty();
        });
        */
        $('#popNotification').fadeOut(400, function () {
            $('#popNotification > div').unbind().empty();
        });
    };

    this.showFollowDialog = function () {
        self.showDialog(
            'Quan tâm Zing News',
            '<p>Trở thành fan của Zing News trên Facebook để nhận tin hot nhất từ Zing News</p>' +
            '<div>' +
                '<iframe src="//www.facebook.com/plugins/likebox.php?href=https%3A%2F%2Fwww.facebook.com%2Fzing.vn&amp;width=200&amp;height=62&amp;colorscheme=light&amp;show_faces=false&amp;header=false&amp;stream=false&amp;show_border=true&amp;appId=622829237762080" scrolling="no" frameborder="0" style="border:none;overflow:hidden;width:100%;height:70px;border:1px solid #ccc;border-radius:5px;margin-top:10px;" allowTransparency="true"></iframe>' +
            '</div>'
        );
    };

    /**
     * Mechanism to get current selected text
     */
    this.getSelection = function () {
        if (window.getSelection) {
            return window.getSelection();
        } else if (document.getSelection) {
            return document.getSelection();
        }
        return false;
    };

    /**
     * Mechanism to automatically attach article link when user copy text
     */
    this.insertCopy = function () {
        var body_element = document.getElementsByTagName('body')[0];
        var selection = self.getSelection();
        if (selection === false) return;
        if (selection.toString().length < 500) return;        
        var pagelink = "<br /><br /> Bài viết: <a href='" + document.location.href + "' target='_blank'>" + document.location.href + "</a><br /><br /><a href='http://news.zing.vn' title='Zing News' target='_blank' style='display:block;font-size:0;line-height:0;'>Nguồn Zing News</a><br />";
        // change this if you want
        var copytext = selection + pagelink;
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        body_element.appendChild(newdiv);
        newdiv.innerHTML = copytext;
        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {
            body_element.removeChild(newdiv);
        }, 0);
    };

    /**
     * Mechanism to display fullscreen any element
     */
    this.launchFullScreen = function (element) {
        //ga('send', 'event', 'Slideshow', 'Switch fullscreen', window.location.pathname);
        if (element.requestFullScreen) {
            element.requestFullScreen();
        } else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
        } else if (element.webkitRequestFullScreen) {
            element.webkitRequestFullScreen();
        }
    };
    this.cancelFullscreen = function () {
        if (document.cancelFullScreen) {
            document.cancelFullScreen();
        } else if (document.mozCancelFullScreen) {
            document.mozCancelFullScreen();
        } else if (document.webkitCancelFullScreen) {
            document.webkitCancelFullScreen();
        }
    };
    this.isFullScreen = function () {
        var fullscreenElement = document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement;
        return (fullscreenElement != null);

    };
    this.isFullscreenEnable = function () {
        return document.fullscreenEnabled || document.mozFullScreenEnabled || document.webkitFullscreenEnabled;
    };

    /**
     * Scroll to top
     */
    this.scrollTo = function (pos) {
        var dest = pos || 0;
        $("html, body").animate({
            'scrollTop': dest + 'px'
        }, Math.abs($(window).scrollTop() - dest) / 5);
    };


    this.getPageType = function () {
        if (cachedPageType) {
            return cachedPageType;
        }

        var pathname = window.location.pathname,
            pageType = '';

        if (pathname == '/' || pathname.indexOf('index.html') > 0) {
            pageType = 'home';
        } else if (/-post[0-9]+\.html/i.test(pathname)) {
            pageType = 'article';
        } else if (/\/tag\/[^\.]*\.html/i.test(pathname)) {
            pageType = 'tag';
        } else if (/\/tim-kiem\/[^\.]*\.html/i.test(pathname)) {
            pageType = 'search';
        } else if (/\/tieu-diem\/[^\.]*\.html/i.test(pathname)) {
            pageType = 'topic';
        } else {
            pageType = 'category';
        }

        cachedPageType = pageType;

        return pageType;
    };
}

function InfiniteArticle() {
    var articleList = [],
        PAGEVIEW_TRACKED = [],
        STOPPED = false,
        IS_SCROLLING_TO = false,
        currentArticleIndex = -1,
        $elements,
        $contentStack,
        $discover,
        $window,
        article,
        currentState,
        scrollState;

    var scrollToArticle = function(url) {
        var articleId = getArticleId(url);
        var $article = $('section.article_content[data-id='+ articleId +']');
        if ($article.length) {
            IS_SCROLLING_TO = true;
            //var top = $article.offset().top;
            //console.log(top);
            //$(window).scrollTop(top);
            //console.log($(window).scrollTop());


            //$article[0].scrollIntoView();
            log('Scroll to article '+url);
            switchArticle($article[0], true);

        }
    };

    var switchArticle = function(elm, manual) {
        var $elm = $(elm),
            url = $elm.data('src');

        $elm.removeClass('inactive');

        // saved read article so that we don't show it again
        //var $prev = $elm.prevAll('.article_content');

        var tracker = page.storage.load('history');
        if(tracker==null || tracker===false) {tracker = "";}
        var current_article = $elm.attr('data-id');
        if (tracker.search(current_article)<0) {
            log('Save read article #'+current_article);
            tracker += current_article+',';
            page.storage.insert('history',tracker);
        }


        if (!currentState) {
            currentState = url;
        }
        scrollState = url;

        //log('Scroll State: '+scrollState);


        if (scrollState != currentState || manual) {
            var tmpUrl = url.split('#')[0];
            currentState = scrollState;
            //log('Current State: '+currentState);

            article.renderFacebookWidgets(url, true);
            if (PAGEVIEW_TRACKED.indexOf(tmpUrl) === -1) {
                PAGEVIEW_TRACKED.push(tmpUrl);

                var tmp = url.split('/'),
                    path = tmp[tmp.length - 1];

                var cate = '';

                if ( typeof cate_path != "undefined") {
                    cate = cate_path+'/';
                }

                log('Sending pageview '+path.replace(/#.*/ig,''));

                ga('send', 'pageview', {
                    'page': '/' + cate + path.replace(/#.*/ig,'')+'#inline-load',
                    'title': $elm.data('title').replace(/\s-[^-]*\s-\sZing News/gi, '')
                });


                $('body').append($('<img>', {
                    'width' : 1,
                    'height' : 1,
                    'src' : 'http://log.news.zing.vn/Counter.aspx?key=story&prm='+$(elm).attr('data-id')+'&rand=' + Math.random()
                }).css('position', 'absolute'));


                $('body').append($('<img>', {
                    'width' : 1,
                    'height' : 1,
                    'src' : 'http://log.news.zing.vn/Counter.aspx?key=all&prm=&rand=' + Math.random()
                }).css('position', 'absolute'));


            }

            if (!manual) {
                // use replaceState instead of pushState so that when user hit back, we will move back to previous page
                History.replaceState({}, $elm.data('title'), tmpUrl);
            } else {
                log('Manual',manual);
                setTimeout(function() {
                    elm.scrollIntoView();
                    //log($(elm).offset().top);
                    //page.scrollTo($(elm).offset().top);
                }, 0);
            }
        }
    };

    var onScroll = function(e) {
        if (IS_SCROLLING_TO) {
            IS_SCROLLING_TO = false;
            return;
        }

        //log(e);

        $elements.each(function(i, elm) {
            if (isElementInViewport(i, elm)) {
                showArticle(elm);
                return false;
            }
        });

        var b = $(this);
        b.data("scrollTimeout") && clearTimeout(b.data("scrollTimeout"));
        b.data("scrollTimeout", setTimeout(onScrollStop, 250, this));
    };

    var onScrollStop = function() {
        var length = $contentStack.length,
            offsetTop = Math.round($(window).height() / 2),
            articleVisible = false;

        $contentStack.addClass('inactive').each(function(i, elm) {
            var $elm = $(elm);
            if (isElementInViewport(i, elm, offsetTop)) {
                articleVisible = true;
                currentArticleIndex = i;
                switchArticle(elm);
                return false;
            }
        });

        if (!articleVisible) {
            switchArticle($contentStack.get(currentArticleIndex));
        }
    };

    var getArticleId = function(url) {
        var matches = url.match(/-post([0-9]+)\.html/i);
        return matches && matches[1] ? matches[1] : 0;
    };

    var showArticle = function(elm) {
        var $elm = $(elm),
            url = $elm.data('src'),
            articleId = $elm.data('id');

        if ($elm.hasClass('loading') || !url) {
            return;
        }

        $elm.addClass('loading');

        $.ajax({
            url: 'http://news.zing.vn/api/mobile/a' + articleId + '.json',
            dataType: 'json',
            success: function(json, textStatus, jqXHR) {
                var data = json.data[0],
                    html;

                var layout = 'article_layout';
                if(data.type=='picture' || data.type=='video') {
                    layout = 'pictures_layout';
                }

                //log(data);

                html = '<section class="article_content '+layout+' inline inactive">' +
                        /*
                        (articleList.length > 0 ?
                            '<div class="autoLoadNotice">' +
                                'Zing.vn tự động tải bài kế tiếp giúp bạn đọc dễ dàng hơn ' +
                                '<a href="#">Tắt chế độ tự động tải</a>' +
                            '</div>' : '') +
                        */
                        '<header>' +
                            '<p class="cate" itemprop="articleSection">' + data.catechild + ' </p>' +
                            '<time datetime="' + data.time + '">' + data.time + '</time>' +
                            '<h1 itemprop="name">' + data.title + '</h1>' +
                            '<div class="summary">' +
                            '<p itemprop="description">' + data.summary + '</p>' +
                            '</div>' +
                        '</header>' +
                        '<article><div class="content" itemprop="articleBody">' + data.content + '</div>';
                html += '<div id="credit">';
                if (data.author) {html += '<p class="author">'+data.author+'</p>';}
                if (data.credit) {html += '<p class="credit">'+data.credit+'</p>';}
                html += '</div>';
                html += '<div class="fb-like" data-href="http://news.zing.vn/zingnews-post'+articleId+'.html"></div>';
                html += '</article>';

                if (data.type!='picture' && data.relate && data.relate.length > 0) {
                    html += '<aside class="sidebar">' +
                            '<section class="related">' +
                            '<header>' +
                            '<h1>Liên quan</h1>' +
                            '</header>';
                    for (var i = 0, length = data.relate.length; i < length; i++) {
                        var relate = data.relate[i];

                        html += '<article>' +
                            '<header>' +
                            '<h1>' +
                            '<a href="' + relate.link + '">' + relate.title + '</a>' +
                            '</h1>' +
                            '</header>' +
                            '</article>';
                    }

                    html += '</section>';
                    html += '<div class="floating">' + $('.article_layout aside.sidebar div.floating').html() + '</div>';
                    html += '</aside>';
                }

                html += '</section>';

                var $section = $(html);
                $section.data({
                    title: data.title,
                    src: url
                });

                $section.attr('data-id', articleId);

                $section.find('.autoLoadNotice').on('click', function(e) {
                    e.preventDefault();

                    STOPPED = true;
                    $(window).off('scroll', onScroll);

                    $(this).fadeOut(function() {
                        $(this).remove();
                    });
                });

                $('.pTitle', $section).remove();
                $('.pHead', $section).remove();

                $elm.after($section);
                $elm.remove();

                var $content = $('article > .content', $section);
                article.formatContent($content);
                article.renderInnerVideo($content);
                article.renderInteractiveContent($content);
                article.renderTablePicture($content);
                article.renderComment($content);


                if (data.type!='video') {
                    //article.renderMetaBox($content);
                }


                $elements = $('.lazy_article');
                new FullscreenSlideshow().init($section);

                updateContentStack();
                page.socialplugin.updateSocialBox($section.find('.fb-like'));
                insertLazyElm();

                //History.pushState({}, data.title, url);


            }
        });
    };

    var updateContentStack = function() {
        $contentStack = $('.article_content');
    };

    var isElementInViewport = function(index, el, offsetTop) {
        var $elem = $(el),
            viewport = {
                top: $window.scrollTop(),
                left: $window.scrollLeft()
            };

        offsetTop = offsetTop || 0;

        viewport.right = viewport.left + $window.width();
        viewport.bottom = viewport.top + $window.height();
        var bounds = $elem.offset();
        bounds.right = bounds.left + $elem.outerWidth();
        bounds.bottom = bounds.top + $elem.outerHeight();

        if (viewport.top >= bounds.top && el.tagName === 'SECTION') {
            currentArticleIndex = index;
        }

        return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top + offsetTop > bounds.bottom));
    };

    var insertLazyElm = function() {
        if (articleList.length > 0) {
            $elements = $('<div class="lazy_article" style="width:660px;float:left"></div>');
            $elements.data({
                src: articleList[0],
                id: getArticleId(articleList[0])
            });
            $discover.before($elements);
            articleList.shift();
            return $elements;
        }
    };

    var init = function(pArticle) {
        PAGEVIEW_TRACKED.push(window.location.href.split('#')[0]);

        article = pArticle;
        $window = $(window);
        $discover = $('#discover');

        $(".article_content:eq(0)").data({
            src: window.location.href,
            title: document.title
        }).attr('data-id', getArticleId(window.location.href));



        var tracker = page.storage.load('history');
        if(tracker==null || tracker===false) {tracker = "";}

        // first, prioritize article inside article
        

        /*
        $relate_articles = $('.article_content .related article');
        var type_filter = page.article.getArticleType();
        $relate_articles.each(function(i, elm) {
            var href = $('header a', elm).attr('href').replace(/#.+/ig,'');
            var time = new Date($('time',elm).attr('datetime'));
            var age = Math.round((now() - time.getTime())/86400000);
            if (age>30) return;
            if (type_filter=='picture' && !$(elm).hasClass('picture')) {
                return;
            }
            if (type_filter=='text' && $(elm).hasClass('picture')) {
                return;
            }

            var articleid = getArticleId(href);
            if (tracker.search(articleid)<0 && articleList.indexOf(href)<0) {
                articleList.push(href);
            }
        });
        */
        
        // if reader comes from external source (i.e. facebook, google), then show next articles in the list
        if(document.referrer=='' || document.referrer.search('http://news.zing.vn')<0) {
            $next_articles = $('.article_content .next_read article');
            $next_articles.each(function(i, elm) {
                var href = $('header a', elm).attr('href').replace(/#.+/ig,'');
                var articleid = getArticleId(href);
                if (tracker.search(articleid)<0 && articleList.indexOf(href)<0) {
                    articleList.push(href);
                }

            });
        } 
        // if user come from within zing, then only show inner article
        else {
            if(page.article.getArticleType()=='text') {
                var $inner_article = $('article .content .inner-article');
                $inner_article.each(function(i,elm){
                    var href = $('a', elm).attr('href').replace(/#.*/ig,'');
                    var articleid = getArticleId(href);
                    if (tracker.search(articleid)<0 && articleList.indexOf(href)<0) {
                        articleList.push(href);
                    }
                });
            }
        }
        

        if (articleList.length > 0) {
            var $firstElement = insertLazyElm();

            $window.scroll(onScroll);
            updateContentStack();

            var popped = false, initialURL = window.location.href;

            window.addEventListener('popstate', function(e) {

                var initialPop = !popped && window.location.href == initialURL;
                    popped = true;

                if (initialPop) {
                    log('Initial Pop on load');
                    return;
                }

                log('History back!');
                setTimeout(function(){
                    scrollToArticle(window.location.href);
                },0);

            });
        }
    };

    this.isElementInViewport = isElementInViewport;
    this.init = init;
}

/**
 * Article feature
 */
function Article() {
    var articles = $('article'),
        self = this,
        fullscreenSlideshow = new FullscreenSlideshow(),
        cachedArticleFormat,
        isAllowComment,
        shortURL;

    this.commentEnabled = function(){
        if (isAllowComment) return isAllowComment;
        isAllowComment = ($('#comments').length > 0);
        return isAllowComment;
    };


    this.init = function () {
        if(self.getArticleType()=='video') {
            Player.setupVideo();
        }

        if($('#credit .source').length==0) {
            $('.article_content > header .summary').addClass('zing');
        }
        self.renderArticleContent();        
        self.renderSocialPlugins();

        $('#attachments a').on('click',function(e){
            e.preventDefault();
            window.open($(this).attr('href'), $(this).text(), "height=600,width=800");
        });
        $('#metainfo .source a').on('click',function(e){
            e.preventDefault();
            var origin_title;

            page.showDialog(
                'Thông tin trích dẫn',
                '<p>Bài được Zing.vn đăng lại từ nội dung gốc theo liên kết bên dưới.</p>' +
                '<div style="font-weight:bold; font-size:1.1em;border: 1px solid #ccc;padding: 10px;margin-bottom: 10px;">'+$(this).text()+'</div>'
            );
        });

        if (DEVICE.type === 'desktop' && (DEVICE.browser === 'chrome' || DEVICE.browser === 'firefox' || DEVICE.browser === 'safari') && ($('.content').text().search(/Tư liệu/ig)<0) && $('.article_content.article_layout,.article_content.pictures_layout').length > 0) {
            var $firstElement = $('.article_content');
            var $recommend = $('<section>',{'class':'recommendation'});
            var $samecate = $('#discover .same_cate');
            $recommend.html($samecate.html());
            $firstElement.after($recommend);
            //$recommend.find('a').attr('target','_blank');
            $samecate.hide();
            new InfiniteArticle().init(self);

        }

        return this;
    };

    this.getArticleType = function () {
        if (cachedArticleFormat != null) return cachedArticleFormat;
        if ($('body#video').length > 0) {cachedArticleFormat = 'video'; return 'video';}
        if ($('#chuyende').length > 0) {cachedArticleFormat = 'special';return 'special';}
        var $content = $('.article_content');
        if ($content.length > 0) {
            if ($content.eq(0).hasClass('pictures_layout')) cachedArticleFormat = 'picture';
            else if ($content.eq(0).hasClass('article_layout')) cachedArticleFormat =  'text';
            else if ($content.eq(0).hasClass('infographic_layout')) cachedArticleFormat =  'infographic';
            else if ($content.eq(0).hasClass('stream_layout')) cachedArticleFormat =  'stream';
            return cachedArticleFormat;
        }
        cachedArticleFormat = null;
        return cachedArticleFormat;
    };

    this.getArticleId = function (url) {
        if(url) {
            var matched = url.match(/post([0-9]+)\.html/i);
            if (matched != null && matched.length>1) {
                return matched[1];
            } else {
                return null;
            }
        }
        if (page.getPageType() == 'article') {
            return window.location.href.replace(window.location.hash, '').replace(/http.*-post|\.html#*/gi, '');
        }
        return null;
    };

    this.getShortLink = function () {
        if (shortURL) return shortURL;
        var articleId = self.getArticleId();
        if (articleId != null) {
            shortURL = 'http://news.zing.vn/zingnews-post' + articleId + '.html';
        } else {
            shortURL = window.location.href;
        }
        //console.log(shortURL);
        return shortURL;
    };

    // setup link for social
    this.renderSocialPlugins = function (url) {
        url =  url || window.location.href.replace(window.location.hash, '');

        var article = {
            title: $('#content > header h1').text(),
            url: url,
            summary: $('#content > header .summary p').html()
        };

        var $shareButtons = $('.share_buttons');
        $shareButtons.find('li a').off('click');
        $shareButtons.find('li a').on('click', function(e) {
            e.preventDefault();
            var $this = $(this),
                $parent = $this.parents('li'),
                url,
                newWindow;

            if ($parent.hasClass('btn_facebook')) {
                if (page.comment.FBAvailable) {
                    FB.ui({
                        method: 'feed',
                        link: article.url,
                        ref: 'InnerArticle'
                    });
                } else {
                    alert("Không truy cập được vào Facebook");
                }
            } else if ($parent.hasClass('btn_zingme')) {
                url = 'http://link.apps.zing.vn/share?u=' + encodeURIComponent(article.url) + '&t=' + encodeURIComponent(article.title) + '&desc=' + encodeURIComponent(article.summary);
                newWindow = window.open(url, "", 'width=500,height=300,scrollbars=no');
                if (window.focus) {
                    newWindow.focus();
                }
            } else if ($parent.hasClass('btn_google')) {
                url = 'https://plus.google.com/share?url=' + encodeURIComponent(article.url);
                newWindow = window.open(url, "", 'menubar=no,toolbar=no,resizable=yes,scrollbars=no,height=600,width=550');
                if (window.focus) {
                    newWindow.focus();
                }
            }
        });
    };

    // setup article links on the page, this include attach click tracking mechanism

    this.renderFacebookWidgets = function(url, reRender) {
        var likeBox = '<div class="fb-like" data-href="' + url + '" data-layout="box_count" data-action="like" data-show-faces="false" data-share="true"></div>';
        if (DEVICE.screen!='wide') {
            likeBox = '<div class="fb-like" data-href="' + url + '" data-width="120" locale="en_US" data-layout="button_count" data-show-faces="false" data-share="false"></div>';
        }

        var $btnSocial = $('#pushnotification .btnSocial');
        if ($btnSocial.length > 0) {
            $btnSocial.html(likeBox);
            if (reRender) {
                FB.XFBML.parse($btnSocial[0]);
            }
        }
    };

    this.renderTablePicture = function($cnt) {
        // reformat all table in content
        var $tables = $cnt.find('> table');
        for (var i = 0, j = $tables.length; i < j; i++) {
            var $table = $tables.eq(i);

            $table.attr('cellpadding', "0").attr('cellspacing', "0").removeAttr('height').removeAttr('width').removeAttr('align');
            // if the table has picture, auto reformat
            if ($table.find('img').length > 0) {
                $table.addClass('picture');
                $table.find('td').each(function () {
                    var $this = $(this);

                    if ($this.find('img').length != 0) {
                        $this.addClass('pic');
                    } else {
                        var text = $.trim($this.text());
                        if (text === "" || text === "Nhập mô tả cho ảnh") {
                            $this.remove();
                        } else {
                            $this.addClass('caption');
                        }
                    }
                });
                $table.find('br').remove();
            }
        };
    };

    this.renderInnerVideo = function($cnt) {
        $('.inner-video a', $cnt).on('click',function(e){
            var $this = $(this);
            e.stopPropagation();
            e.preventDefault();
            var videolink = $this.attr('href')+'#singleplayer';

            var iframe = $('<iframe>',{'src':videolink}).css({'width':'100%', 'height':'100%'});
            $this.parents('.inner-video').html(iframe);
        });
    };

    this.renderInteractiveContent = function($cnt) {
        $('.interactive-content a', $cnt).on('click',function(e){
            e.preventDefault();
            var $this = $(this),
                winWidth = parseInt($this.attr('viewW')),
                winHeight = parseInt($this.attr('viewH')),
                videowindow = window.open($this.attr('href'), "interactive", "width="+winWidth+", height= "+winHeight+", left=300, top=300, resizable=no, toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no");
        });
    };

    this.renderInfographicContent = function($cnt) {
        var $infographics = $cnt.find('.picture img');
        var src;
        for (var i = 0, j = $infographics.length; i < j; i++) {
            var $zoomer = $infographics.eq(i);
            src = $zoomer.attr('src');
            $zoomer.after('<span class="zoom-instruct"></span>');

            //$(zoomer).attr('src',src.replace(/\/w\d+\//,'/w1024/'));
            $zoomer.attr('data-zoom-image',src.replace(/\/w\d+\//,'/'));

            $zoomer.ensureLoad(function() {
                var originWidth = $zoomer.width();
                var originHeight = $zoomer.height();

                log('Original Loaded | '+originWidth + ":" + originHeight);

                // if this is a vertical infographic that is long enough, don't do zoomer
                if (originHeight/originWidth > 1.5) {
                    $zoomer.siblings('.zoom-instruct').remove();
                    return;
                }
                var fullimg = $('<img>',{'src':src.replace(/\/w\d+\//,'/')}).ensureLoad(function(){
                    var fullWidth = $(fullimg).width();
                    var zoomtype = 'inner';
                    // if the zoom ratio is less than 2, don't magnify
                    if (fullWidth/originWidth < 2) {
                        $zoomer.siblings('.zoom-instruct').remove();
                        return;
                    }
                    loadPlugin('elevateZoom', 'elevateZoom.js', function(){
                        log('Initialize zoom');
                        $zoomer.siblings('.zoom-instruct').remove();
                        $zoomer.elevateZoom({
                            responsive: true,
                            loadingIcon:true,
                            zoomType:zoomtype,
                            lensSize:'300',
                            cursor:'move',
                            loadingIcon:'http://stc.v3.news.zing.vn/css/img/icon_loading_small.gif'
                        });

                    });
                });
                $('body').append($(fullimg).hide());
            });
        }
    };

    this.renderComment = function($cnt) {
        var $parent = $cnt.parents('section.article_content');
        var $cmt = $('<div>');
        var articleid = $parent.attr('data-id');
        if(articleid==null) {articleid=self.getArticleId();}
        new Comment(articleid,$cmt);
        $parent.append($cmt);
    };

    this.renderMetaBox = function($cnt) {
        var $metabox = $cnt.parents('article').find('#metainfo');
        var articleid = $cnt.parents('.article_content').attr('data-id');
        if(articleid==null) {articleid=self.getArticleId();}
        var $rating;
        log('Setting up metabox for article#'+articleid);
        //log($cnt.parents('.article_content'));
        if($metabox.length>0) {
            $metabox.addClass('metabox').attr('id','');
            if($metabox.find('#articleRating').length > 0) {
                $rating = $('#articleRating');
            } else {
                $rating = $('<div>');
                $metabox.append($rating);
            }
            self.setupRating(articleid,$rating);
        } else {
            $metabox = $('<div>').addClass('metabox');
            $cnt.parents('article').append($metabox);
            $rating = $('<div>');
            self.setupRating(articleid,$rating);
            $metabox.append($rating);
        }
    };

    this.formatContent = function($cnt) {
        $cnt.find('*:not(".percent,.formatted")').removeClass("pBody").removeAttr("style");
        // auto wrap textNode and clear empty nodes
        var textNode = $cnt.contents().filter(function () {
            return this.nodeType == 3;
        });
        for (var a = 0, b = textNode.length; a < b; a++) {
            if ($(textNode[a]).text() == "" || $(textNode[a]).text() == "\n") $(textNode[a]).remove();
            else {
                $(textNode[a]).wrap('<p>');
            }
        };

        // remove unncessary tags
        $cnt.find('> p ~ br').remove();
        $cnt.find('p > br + br').after('<span class="linebreak"></span>').remove();
        $cnt.find('> p').filter(function () {
            return ($(this).find('img').length == 0) && ($(this).find('iframe').length == 0) && ($.trim($(this).text()) == "");
        }).remove();
        $cnt.find('> p').filter(function(){
            return ($(this).find('img').length>0 && $(this).text().trim()=='') ;
        }).addClass('inline-image');
        $cnt.find('> em').prev('p').css('display', 'inline');
    };

    /**
     * Format article content & setup tools
     */
    this.renderArticleContent = function () {
        var $content = $('article > .content');

        if ($content.length == 0) {
            return;
        }

        this.renderInnerVideo($content);
        this.renderInteractiveContent($content);
        this.renderTablePicture($content);

        // render toolbox (left side box) for article page
        var $pushNotification = $('#pushnotification');
        if ($pushNotification.length == 0) {

            $('body').append($('<div>', {
                'id': 'pushnotification'
            }).html("<a href='javascript:page.scrollTo();' class='button btnToTop'>Đầu trang</a>"+'<div class="wrapper"></div>'));
            $('body').append("<a href='javascript:page.scrollTo();' class='button btnToTop'>Đầu trang</a>");

            $pushNotification = $('#pushnotification');

            $pushNotification.find('.wrapper').append($('<div>', {
                'class': 'actions'
            }));

            $pushNotification.find('.wrapper .actions').html(
                "<a href='http://news.zing.vn' class='button btnHome'>Trang chủ</a>" +
                "<div id='font'><a href='#' class='btnRegularFont'>Abc</a><a class='btnSerifFont' href='#'>Abc</a></div>" +
                "<div class='btnSocial'></div>"+
                "<a href='javascript:page.article.reportError();' class='button btnError'>Báo lỗi bài viết</a>"
            );

            self.renderFacebookWidgets(self.getShortLink());

            if ($.cookie('font') == null) {
                $pushNotification.find('.btnRegularFont').addClass('current');
            } else {
                $pushNotification.find('.btnSerifFont').addClass('current');
            }
            $pushNotification.find('#font a').on('click', function () {
                if ($(this).hasClass('btnSerifFont')) {
                    $.cookie('font', 1, {
                        expires: 100,
                        path: '/'
                    });
                    $('body').addClass('serif');
                    //ga('send', 'event', 'Article', 'Change Font', 'Serif');
                } else {
                    $.removeCookie('font');
                    $('body').removeClass('serif');
                    //ga('send', 'event', 'Article', 'Change Font', 'Standard');
                }
                $pushNotification.find('#font a').removeClass('current');
                $(this).addClass('current');
                return false;
            });


        }

        // automatically insert article link on copy of text
        $content.bind('copy', function () {
            page.insertCopy();
            //ga('send', 'event', 'Article', 'Copy Text', window.location.pathname);
        });

        // grammar report mechanism activate when user select text
        $content.bind('mouseup', function (e) {
            var selectedText = page.getSelection();
            if (selectedText != false && selectedText != '') {
                page.showBottomBar();
                var $btnError = $pushNotification.find('.btnError');
                if ($btnError.hasClass('active')) {
                    $btnError.removeClass('active');
                } else {
                    $btnError.addClass('active');
                }
            } else {
                $pushNotification.find('.btnError').removeClass('active');
            }
        });

        // format content
        if(page.article.getArticleType()!='special') {
            // clear all styles
            this.formatContent($content);
            /*
            $content.find('*:not(".percent,.formatted")').removeClass("pBody").removeAttr("style");
            // auto wrap textNode and clear empty nodes
            var textNode = $content.contents().filter(function () {
                return this.nodeType == 3;
            });
            for (var a = 0, b = textNode.length; a < b; a++) {
                if ($(textNode[a]).text() == "" || $(textNode[a]).text() == "\n") $(textNode[a]).remove();
                else {
                    $(textNode[a]).wrap('<p>');
                }
            };

            // remove unncessary tags
            $content.find('> p ~ br').remove();
            $content.find('p > br + br').after('<span class="linebreak"></span>').remove();
            $content.find('> p').filter(function () {
                return ($(this).find('img').length == 0) && ($(this).find('iframe').length == 0) && ($.trim($(this).text()) == "");
            }).remove();
            $content.find('> p').filter(function(){
                return ($(this).find('img').length>0 && $(this).text().trim()=='') ;
            }).addClass('inline-image');
            $content.find('> em').prev('p').css('display', 'inline');
            */
        }


        // Zooming/slideshow mechanism for image in article
        fullscreenSlideshow.init($('#content'));

        // setup infographic content
        if(page.article.getArticleType()=='infographic') {
            this.renderInfographicContent($content);
        }

        if(self.commentEnabled()) {
            this.renderComment($content);
        }

        self.renderMetaBox($content);
    };


    /**
     * Send user feedback on article content
     */
    this.reportError = function () {

        var selectedText = page.getSelection();
        if (selectedText == false || selectedText == null) {
            selectedText = "";
        }
        selectedText = $.trim(selectedText);

        var dialogMessage = '';
        if (selectedText.length > 0) {
            dialogMessage += '<p class="label">Nội dung chứa lỗi:</p>' +
                    '<blockquote class="error"><p>'+ selectedText +'</p></blockquote>' +
                    '<p class="label">Giải thích/sửa lỗi (không bắt buộc):</p>';
        } else {
            dialogMessage += '<p class="label">Nhập thông tin báo lỗi vào ô bên dưới</p>';
        }

        dialogMessage += '<div><textarea id="errorContent"></textarea></div>';

        page.showDialog(
            'Báo lỗi thông tin bài viết',
            dialogMessage, {
                submit: {
                    text: 'Gửi báo lỗi',
                    action: function () {
                        var errorContent = $.trim($('#errorContent').val());
                        if (errorContent.length > 0) {
                            var reportContent = '';
                            if (selectedText.length > 0) {
                                reportContent += "[Lỗi]\n" + selectedText + "\n";
                            }
                            reportContent += "[Sửa]\n" + errorContent;

                            $.ajax({
                                type: 'POST',
                                url: "http://news.zing.vn/api/grammarreport.aspx?id=" + page.article.getArticleId(),
                                cache: false,
                                data: {
                                    content: reportContent
                                }
                            }).done(function () {
                                //ga('send', 'event', 'Article', 'Report Error', window.location.pathname);
                                //console.log($.cookie('grammar'));
                                page.closeDialog();
                                page.showDialog(
                                    'Báo lỗi thông tin bài viết',
                                    '<p>Cám ơn bạn đã báo lỗi bài này. Zing News sẽ cố gắng sửa nhanh nhất lỗi bạn đã báo. Bạn sẽ có thể báo lỗi bài này lại sau 24 tiếng.</p>'
                                );
                            });
                        } else {
                            page.closeDialog();
                            page.showDialog(
                                'Thông báo',
                                '<p>Để báo lỗi, bạn cần nhập nội dung có lỗi trong bài, hoặc chú thích thông tin bị sai của bài viết.</p>'
                            );
                        }

                    }
                }
            }
        );
    };

    /**
     * Setup rating  article
     */
    this.setupRating = function(id, parent){
        if (id==null) return;
        log('Setup rating box for article '+id);
        var ratingList = page.storage.load('ratingList');
        var articleid = id;
        var $articleRating = $(parent);

        if (ratingList == null || ratingList === false) {
            //log('Rating list is empty');
            ratingList = "";
        }

        if (ratingList.search(articleid) >= 0) {
            log('Article is already rated!');
            $articleRating.remove();
            return;
        }


        $articleRating.addClass('ratingbox').attr('data-id',articleid).html(
            '<p class="heading">ĐÁNH GIÁ BÀI VIẾT</p>'
            +'<p>Giúp Zing.vn ngày càng nâng cao chất lượng nội dung bằng cách cho chúng tôi biết bạn đánh giá thế nào về bài viết này:</p>'
            +'<ul>'
            +'<li class="ratingGood"><strong>Rất tốt!</strong> Thông tin nhanh, nội dung trung thực và khách quan.</li>'
            +'<li class="ratingNormal"><strong>Bình thường:</strong> Thông tin hữu ích, nội dung không lỗi.</li>'
            +'<li class="ratingBad"><strong>Kém:</strong> Nội dung không có giá trị, nhiều lỗi</li>'
            +'</ul>'
        );


        $articleRating.find('li').on('click',function(){
            var feedback = 2,
                score = 0;
            if ($(this).hasClass('ratingGood')) {
                feedback = 1;
                score = 1;
            } else if ($(this).hasClass('ratingBad')) {
                feedback = 3;
                score = -1;
            }

            $.ajax({
                type: 'POST',
                cache: false,
                url: "http://news.zing.vn/api/rating.aspx?id=" + articleid + "&value=" + feedback
            }).success(function() {
                //ga('send', 'event', 'Article', 'Rating', window.location.pathname, score);
                // save the article id  so that we don't display message anymore
                ratingList += articleid+',';
                page.storage.insert('ratingList', ratingList);
                if (feedback == 3) {
                    $articleRating.html('<div class="result">Cám ơn bạn đã đánh giá. Ban biên tập đã được thông báo về ý kiến của bạn và sẽ cố gắng nâng cao chất lượng bài viết.</div>');
                } else {
                    $articleRating.html('<div class="result">Zing cám ơn bạn đã đánh giá và rất vui vì bài viết đã đem lại thông tin hữu ích cho bạn.<br /><a href="#share">Chia sẻ bài viết cho bạn bè</a></div>');
                    $articleRating.find('.result a').on('click', function(e){
                        e.preventDefault;
                        if (page.socialplugin.FBAvailable) {
                            FB.ui({
                                method: 'feed',
                                link: page.article.getShortLink(),
                                ref: 'InnerArticle'
                            });
                        } else {
                            alert("Không truy cập được vào Facebook");
                        }
                    });
                }

            }).fail(function(){

            });
        });

        $articleRating.show();
    };
}

/**
 * Facebook intergration
 */
function SocialPlugin() {
    var self = this;

    this.FBAvailable = false,this.isFBLogin = false;
    this.userinfo = null;


    // initialization, checking facebook connection,...
    this.init = function () {
        jQuery.ajax({
            async: true,
            type: 'GET',
            url: '//connect.facebook.net/vi_VN/all.js#xfbml=1&appId=622829237762080',
            dataType: 'script',
            cache: true,
            data: null,
            complete: function (xhr, status) {
                // setup social components
                if (xhr.status == 200) {
                    self.FBAvailable = true;
                    log('Facebook is accessible!');
                    window.fbAsyncInit = function () {
                        if (FB) {
                            FB.init({
                                appId: APP_ID,
                                logging: false,
                                status: true, // Check Facebook Login status
                                cookie: true
                            });

                            $('body').addClass('fbonline');

                            if (DEVICE.screen == 'wide' && page.getPageType() == 'article' && $('body').attr('id') != 'video' && $('#infographic').length < 0) {
                                log('Setup Recommendation Bar');
                                $('body').append('<div class="fb-recommendations-bar" data-trigger="50%" data-site="news.zing.vn" data-num-recommendations="3" data-max-age="1" data-read-time="10" data-side="right" data-action="recommend"></div>');
                            }

                            if (page.getPageType() == 'home') {
                                log('Setup Fanpage Box');
                                $('.sidebar #promotedposts').after('<div class="fb-like-box" data-href="https://www.facebook.com/zing.vn" data-width="300" data-height="190" data-colorscheme="light" data-show-faces="true" data-header="false" data-stream="false" data-show-border="false" style="float:left;margin-bottom:10px; border:1px solid #ccc;"></div>');
                            }

                            if (page.getPageType() == 'article') {
                                var $likeButtons = $('.article_content article .fb-like');
                                $likeButtons.each(function(index, elm){
                                    page.socialplugin.updateSocialBox(elm);
                                });
                            }

                            // show follow button on toolbox
                            if ($('#toolbox .toTop').length > 0) {
                                $('#toolbox .toTop').after('<li class="facebook"><a href="javascript:page.showFollowDialog();" title="Quan tâm trên Facebook"><span>Facebook</span></a></li>');
                            }

                            self.getUserInfo(function(user){
                                if(user==null) return;
                                $('.commentbox .content label').html(
                                    '<img src="'+user.avatar+'" width="40" height="40" class="avatar" />'
                                    +'<strong>'+user.name+'</strong> (<a href="javascript:page.socialplugin.logout();" title="Thoát">Thoát</a>)'
                                );
                                $('.commentbox .btnSubmit').after('<label class="sharefb"><input type="checkbox" value="1" checked>Chia sẻ Facebook</label>');
                            });

                            FB.Event.subscribe('edge.create', function(url,elm){
                                $(elm).parents('.btnSocial').css('overflow','visible');
                            });

                            FB.XFBML.parse();

                        }
                    };
                }
                else {
                    log('Facebook is not accessible!');
                    $('#pushnotification .btnFacebook').hide();
                    $('.fb-like').hide();
                }

            }

        });

    };

    // a very simple way to generate identification for user
    this.generateUID = function(){
        var identifier = (new Date()).getTime();
        identifier = identifier.toString()+Math.round(Math.random()*10000);
        return 'user_'+identifier;
    };

    this.showFanpagePopup = function(){
        if (FB==undefined) return;
        if (self.userinfo==null) return;
        if (self.isFBLogin===false) return;
        FB.api({
            method: 'fql.query', 
            query:  'SELECT uid FROM page_fan WHERE uid='+self.userinfo.id+' AND page_id=1414411772114879'
        }, function(resp) {
            if (resp.length) {
                // already a fan, so no asking                
            } else {
                page.showFollowDialog();
            }
        });
    }

    // login
    this.login = function(callback, facebook){
        log('Logging user in...');
        // if user already login
        if(self.userinfo) {
            if (callback && typeof callback == 'function') {
                callback(self.userinfo);
            }
        }

        // if facebook available, and we are not on mobile
        if((DEVICE.type=='desktop')&& (facebook==null || facebook!==false) && self.FBAvailable) {
            FB.login(function(response) {
                if (response.authResponse) {
                    log("Login with FB successful");
                    self.isFBLogin = true;
                    self.getUserInfo(function(user){
                        if(callback && typeof callback=='function') {
                            callback(user);
                        }
                    });
                } else {
                    log('User cancelled login or did not fully authorize.');
                    self.login(callback, false);
                }
            },{scope: 'publish_actions,publish_stream'});
            return;
        }

        // else ask user for info
        page.showDialog(
            'Thông tin người dùng',
            '<p>Để gửi bình luận, bạn vui lòng cung cấp thông tin:</p>'
            +'<form>'
            +'<p><label>Họ và tên</label> <input type="text" id="comment_name" maxlength="25"  /></p>'
            +'<p><label>Email</label> <input type="text" id="comment_email"  /></p>'
            +'</form>',
            {
                submit: {
                    text: 'Gửi bình luận',
                    action: function(){
                        var username = $('#comment_name').val().trim();
                        var useremail = $('#comment_email').val().trim();
                        if(username!='' && useremail!='') {
                            log('New user. Generate new user!',self.userinfo);
                            self.userinfo = {
                                id: self.generateUID(),
                                name: username,
                                email:useremail,
                                avatar:''
                            };

                            //page.storage.insert('userinfo',JSON.stringify(self.userinfo));

                            if(callback && typeof callback=='function') {
                                callback(self.userinfo);
                            }
                            page.closeDialog();
                        } else {
                            alert('Bạn cần phải cung cấp tên và email để gửi bình luận!');
                        }

                    }
                },
                cancel: {
                    text:'Đóng',
                    action: function(){
                        log('User provide no information!');
                        page.closeDialog();
                        setTimeout(function(){
                            page.showDialog(
                                'Bình luận chưa được gửi',
                                '<p>Bạn chưa đăng nhập hoặc chưa điền thông tin cá nhân. Để gửi bình luận, bạn cần phải cung cấp thông tin người dùng. Vui lòng thử lại.</p>'
                            );
                        },100);

                    }
                }
            }
        );
    };

    // Logout
    this.logout = function() {
         self.userinfo = null;
         page.storage.clear('userinfo');
          if (typeof FB == undefined) return;
          FB.logout(function(response){
              self.userinfo=null;
              page.showDialog(
                    'Thông báo',
                    '<p>Bạn đã đăng xuất thành công!</p>'
              );
              if(page.getPageType()=='article' && page.article.commentEnabled()) {
                  $('.commentbox label').html('Bình luận');
              }
          });
    };

    // Get user info
    this.getUserInfo = function(callback){
        log('Checking login status');

        // if already checked before
        if (self.userinfo!=null) {
            log('User already login!');
            if(callback && typeof callback=='function') {
                log(self.userinfo);
               callback(self.userinfo);
            }
            return;
        } else {
            log('User not login yet');
        }


        if (DEVICE.type!='desktop' || !self.FBAvailable) {
            log('On mobile or FB is not available, let user enter manually');
            if(callback && typeof callback=='function') callback();
            return;
        };


        // fb available, looking for fb info first
        // log('Checking Facebook login status');
        FB.getLoginStatus(function(response) {
            if (response.status === 'connected') {
                var uid = response.authResponse.userID;
                var accessToken = response.authResponse.accessToken;
                $('body').addClass('fbAuthorized');

                FB.api('/'+uid, function(user) {
                    self.userinfo = {
                        name: user.name,
                        email: user.username+'@facebook.com',
                        id:user.id,
                        avatar:'http://graph.facebook.com/'+user.id+'/picture?type=square'
                    };
                    self.isFBLogin = true;
                    log('Login with Facebook as '+self.userinfo.name);
                    //page.storage.insert('userinfo',JSON.stringify(self.userinfo));
                    if (callback && typeof callback == 'function') {
                        callback(self.userinfo);
                    }

                });
            } else {
                if (callback && typeof callback == 'function') {
                    callback();
                }
            }

        });

    };

    // push comment on facebook
    this.comment = function(content, url, callback){
        log('Attempt share comment on facebook');
        if (typeof FB == undefined || !self.isFBLogin) {
            log('Facebook is not accessible. Share cancel!');
            return;
        }

        log('Sharing article '+url);

        /* using custom open graph action */
        FB.api('me/zing_news:comment', 'post', {
            article : url,
            message: content,
            'fb:explicitly_shared': true
        }, function(response) {
            log(response);
            if (response && !response.error) {
                log ('Comment posted on Facebook');
                if(callback && typeof callback == 'function') {
                    callback(true);
                }
            } else {
                if(callback && typeof callback == 'function') {
                    callback(false);
                }
                log ('Unable to submit comment to Facebook');
            }
        });
    };



    // share url on facebook
    this.share = function(url) {
        FB.ui({
            method : 'feed',
            link : url,
            display: 'popup'
        }, function(response) {
        });
    };

    // like an url on facebook
    this.like = function(url, callback, message) {

        if (typeof FB == undefined) {
            log('Facebook is not accessible. Like cancel!');
            if(callback) callback(false);
            return;
        }

        log('User like an article: '+url);

        if (!self.isFBLogin) {
            FB.login(function(response) {
                if (response.authResponse) {
                    log("Login with FB successful");
                    self.isFBLogin = true;
                    self.like(url,callback);

                } else {
                    log('User cancelled login or did not fully authorize.');
                    page.showDialog(
                        'Đăng nhập thất bại',
                        '<p>Bạn cần đăng nhập Facebook và cấp quyền để có thể thực hiện tác vụ này. Bạn muốn thử lại?</p>',
                        {
                            submit: {
                                text:'Thử lại',
                                action: function(){
                                    self.like(url,callback);
                                    page.closeDialog();
                                }
                            },
                            cancel: {
                                text:'Đóng',
                                action: function(){
                                    page.closeDialog();
                                    callback(false);
                                }
                            }
                        }
                    );

                }
            },{scope: 'publish_actions,publish_stream'});
            return;
        }

        if(message==null) {
            page.showDialog(
                'Nội dung chia sẻ',
                '<p>Chia sẻ cảm nghĩ của mình về bài viết:</p>'+
                '<textarea id="like_comment" style="margin-top:10px; padding:10px; width:100%; height: 100px;"></textarea>',
                {
                    submit: {
                        text:'Chia sẻ lên Facebook',
                        action: function(){
                            var like_message = $('#like_comment').val().trim();
                            self.like(url,callback,like_message);
                            page.closeDialog();
                        }
                    },
                    cancel: {
                        text:'Bỏ qua',
                        action: function(){
                            self.like(url,callback,false);
                            page.closeDialog();                            
                        }
                    }
                }
            );
            return;
        }

        var msg = null, fbshare = true;
        if (message===false) {
            fbshare = false;
        } else if (message!="") {
            msg = message;
        }

        FB.api('me/og.likes', 'post', {
            object : url,
            message: msg,
            'fb:explicitly_shared': fbshare
        }, function(response) {
            log(response);
            if ((response.error && response.error.code==3501) || response.id) {
                var actionid;
                if(response.id) actionid = response.id;
                else {
                    actionid = response.error.message.match(/\d+$/i)[0];
                }
                log('Like success: '+url);
                page.socialplugin.showFanpagePopup();
                //page.storage.insert(url,actionid);
                callback(true,actionid);
            } else {
                log('Like fail: '+url);
                callback(false);
            }

        });


    };

    this.updateSocialBox = function(elm) {
        if (typeof FB == undefined) return;
        var $box = $(elm);
        $box.removeClass('fb-like').addClass('socialbox');
        $.ajax({
            //url: 'http://news.zing.vn/api/mobile/a' + articleId + '.json',
            url: 'https://api.facebook.com/method/links.getStats?urls='+$box.attr('data-href')+'&format=json',
            dataType: 'json',
            success: function(json, textStatus, jqXHR) {
                if (json && json.length>0) {
                    $box.html(
                        '<a class="btnLike" href="#like" title="Thích bài viết này"><span>'+json[0].like_count+'</span> Thích bài viết</a>'
                        + '<a class="btnShare" href="#share" title="Chia sẻ bài viết"><span>'+(json[0].share_count+json[0].comment_count)+'</span> Chia sẻ</a>'
                    );
                    $box.find('.btnLike').on('click',function(e){
                        e.preventDefault();
                        var $like = $(this);
                        self.like($box.attr('data-href'),function(result,id){
                             if(result && result===true) {
                                $like.addClass('liked');
                                if(id) {
                                    $like.attr('like',id);
                                    $like.find('span').on('click', function(e){
                                        e.stopPropagation();
                                        e.preventDefault();
                                        log('Unlike article ' + $box.attr('data-href'));
                                        FB.api(id, 'delete', function(response) {
                                            $like.removeClass('liked').removeAttr('like');
                                            $like.find('span').off('click');
                                        });

                                    });
                                }
                             } else {
                                 page.showDialog(
                                     'Lỗi mạng',
                                     '<p>Có lỗi xảy ra khi thực hiện tác vụ bạn yêu cầu. Có thể mạng của bạn không vào được Facebook lúc này. Vui lòng thử lại.</p>'
                                 );

                             }

                        });
                    });
                    $box.find('.btnShare').on('click',function(e){
                        e.preventDefault();
                        self.share($box.attr('data-href'));

                    });
                }
            },
            fail: function(){}
        });
    };

}

/**
 * Comment
 */
function Comment(id, parent) {
    var checktimer, self=this, articleid = id;
    var $comment = $(parent), $commentField, $notes, $btnSubmit,$commentList, $btnMore;


    // fetch approved comments from CMS
    this.fetchComment = function(callback,pagination,timeorder,parent) {
        if(articleid==null) return;
        var commentFeed = 'http://news.zing.vn/api/comment.aspx?action=get&id='+articleid;
        if(!parent) {
            if(pagination) commentFeed += ('&page='+pagination);
            if(timeorder && timeorder===true) commentFeed += ('&sortByTime=1');    
        } else {
            commentFeed += ('&parent_comment_id='+parent);
        }
        
        log('Retrieve comments list: '+commentFeed);
        $.getJSON(commentFeed, function (data) {
            if(callback && (typeof callback == 'function')) {
                callback(data);
            }
        });
    };

    this.renderComment = function(comment, isChild) {
        var comment_html='', $output=$('<li>',{'id':comment.ID});
        var like = (comment.Like==0)?"":comment.Like, dislike = (comment.Dislike==0)?"":comment.Dislike;        
        comment_html += '<p class="meta">';
        if (comment.Avatar.trim()!='') {            
            comment_html += '<img src="'+comment.Avatar+'" width="30" height="30" class="avatar" />';
        } else {
            $output.addClass('noavatar');
        }
        comment_html += '<span class="author">'+comment.DisplayName+'</span> ';
        comment_html += '<span class="time">'+page.formatTime(comment.CreationDate,{'friendly':true})+'</span></p>';                
        comment_html += '<div class="comment-content"><p>'+comment.Comment.replace(/\\n/g,'</p><p>')+'</p></div>';
        comment_html += '<div class="comment-actions"><a class="btnLike" href="#like"><span>'+like+'</span> Thích</a>';
        comment_html += '<a class="btnDislike" href="#dislike"><span>'+dislike+'</span> Không thích</a>';        
        if (isChild==null || isChild===false) {
            comment_html += '<a class="btnReply" href="#reply">Trả lời</a></div>';
        }
        $output.html(comment_html);
        if ((isChild==null || isChild===false) && comment.ReplyCount>0) {            
            
            var $replies = $('<ul>',{'class':'replies'});
            for (var a = 0; a < comment.Replies.length; a++) {
                $replies.append(self.renderComment(comment.Replies[a],true));
            };            
            $output.append($replies);
            if(comment.ReplyCount>3) {
                var $more = $('<a>',{'href':'#','class':'btnMore'}).html('Xem thêm').on('click',function(e){
                    var cur = this;
                    e.preventDefault(); 
                    var parent_comment_id = $(this).parents('li').attr('id');
                    self.fetchComment(function(replies){
                        for (var i = 0; i < replies.length; i++) {
                            if ($('#'+replies[i].ID).length>0) continue;
                            $replies.append(self.renderComment(replies[i]))
                        };
                        $(cur).remove();
                    },1,true,parent_comment_id);
                });
                $output.append($more);
            }
        }
        
        return $output;
    }

    // update comments list
    this.updateComment = function(commentpage, orderbytime){
        var pagination = (commentpage==null)?1:commentpage;
        var comment, comment_content='';
        self.fetchComment(function(data){
            var total_page = Math.floor(parseInt(data.total_comment)/20)+1;
            if (data.comments.length>0 && commentpage==1 && $comment.find('.order').length==0) {
                $commentList.before('<div class="order"><label>Xếp theo: </label><a href="#" class="orderbyimportance current">Hay nhất</a> <a href="#" class="orderbytime">Mới nhất</a></div>');                                
                $comment.find('.order a').on('click',function(e){
                    e.preventDefault();
                    if($(this).hasClass('current')) return;
                    $(this).siblings('.current').removeClass('current');
                    $(this).addClass('current');
                    if($(this).hasClass('orderbyimportance')) {
                        $comment.removeAttr('orderbytime');
                    } else {
                        $comment.attr('orderbytime',1);
                    }
                    $commentList.html('');
                    var orderbytime = ($comment.attr('orderbytime')==1);
                    self.updateComment(1,orderbytime);
                });
            }
            for(var i=0,j=data.comments.length; i<j; i++){                
                $commentList.append(self.renderComment(data.comments[i]));
            };
            $commentList.show();
            $commentList.find('.comment-actions a').off('click').on('click',function(e){
                e.preventDefault();
                var $cmt = $(this);
                var cmt_id = $cmt.parents('li').attr('id');
                var cmt_name = $cmt.parents('li').find('.author').html();
                // click on reply button
                if($cmt.hasClass('btnReply')) {
                    log('User Reply');                    
                    if($cmt.parents('li').find('.reply').length == 0) {
                        var $replyForm = $('<div>',{'class':'reply'}).html('<textarea comment-parent="'+cmt_id+'"></textarea><a href="#" class="btnSubmit disabled">Gửi trả lời</a>');
                        $cmt.after($replyForm);
                        $replyForm.find('.btnSubmit').on('click',function(e){
                            e.preventDefault();
                            $replyForm.hide();
                            var $reply = $(this).parents('.reply').find('textarea');
                            log('Reply to comment: #'+$reply.attr('comment-parent') + ' with content: '+$reply.val());
                            self.submitComment($reply.val(),true,$reply.attr('comment-parent'),function(){
                                if(result===false) {
                                    $replyForm.show();
                                }
                            });
                        });
                    } else {
                        $cmt.parents('li').find('.reply').remove();
                    }

                    return;
                }
                // otherwise, click on like or dislike button
                if($cmt.parents('.comment-actions').hasClass('disabled')) {
                    page.showDialog(
                        'Thông báo',
                        '<p>Bạn đã bình chọn cho bình luận này rồi. Bạn chỉ có thể bình chọn 1 lần cho mỗi bình luận.</p>'
                    );
                    return;
                }

                var article_id = $(this).parents('.commentbox').attr('id').replace('comment-','');
                var cmt_action = 'like';
                if($cmt.hasClass('btnDislike')) cmt_action = 'dislike';
                $.ajax({
                    url:'http://news.zing.vn/api/comment.aspx?action='+cmt_action+'&id='+article_id,
                    type:'POST',
                    dataType:'text',
                    data: {
                        commentid:cmt_id
                    },
                    success:function(data, status, jqXHR){
                        if(data=='') {
                            $cmt.parents('.comment-actions').addClass('disabled');
                            $cmt.addClass('active');
                            var count = $cmt.find('span').text();
                            if(count=='') count=0;
                            $cmt.find('span').text(parseInt(count)+1);
                        } else {
                            log('Action Error');
                        }
                    },
                    fail: function(){
                        log('Error like action for comment #'+cmt_id);
                    }
                });
            });

            if(parseInt(data.current_page)<total_page) {
                $btnMore.attr('nextpage',(data.current_page+1)).show();
            } else {
                $btnMore.hide();
            }

        },pagination,orderbytime);
    };

    // check comment content
    this.checkCommentContent = function(comment,callback){
        // first check if comment is not empty
        if (comment.trim()=='') {
            page.showDialog(
                'Bình luận không có nội dung',
                '<p>Bình luận không thể để trống. Vui lòng chia sẻ vài dòng suy nghĩ của bạn về bài viết.</p>'
            );
            return;
        };
        // check if comment is too short
        var words = comment.split(' ');
        if(words.length < 10) {
           page.showDialog(
                'Bình luận quá ngắn',
                '<p style="margin-bottom:8px;"><strong>Bình luận của bạn quá ngắn!</strong> Ban quản trị sẽ chỉ duyệt nếu bình luận dài tối thiểu 10 chữ. Bạn có muốn tiếp tục?</p><p style="font-size:0.9em;color:#888;">Chú ý: Bạn vẫn có thể gửi bình luận nhưng bình luận của bạn sẽ không vào danh sách chờ duyệt và sẽ không hiển thị.</p>',
                {
                    submit: {
                        text:'Quay lại cập nhật',
                        action:function() {
                            page.closeDialog();
                        }
                    },
                    cancel: {
                        text: 'Gửi bình luận',
                        action: function(){
                            page.closeDialog();
                            if (callback && typeof callback == 'function') {
                                callback();
                            }
                        }
                    }
                }
            );
            return;
        }
        // check if comment is Vietnamese
        if(!isVietnamese(comment)) {
            page.showDialog(
                'Bình luận bằng tiếng Việt có dấu',
                '<p><strong>Zing.vn chỉ đăng bình luận bằng tiếng Việt có dấu!</strong> Nội dung bình luận của bạn không có ký tự tiếng Việt. Bạn có muốn tiếp tục?</p>',
                {
                    submit: {
                        text:'Quay lại cập nhật',
                        action:function() {
                            page.closeDialog();
                        }
                    },
                    cancel: {
                        text: 'Gửi bình luận không dấu',
                        action: function(){
                            page.closeDialog();
                            if (callback && typeof callback == 'function') {
                                callback();
                            }
                        }
                    }
                }
            );
            return;
        }

        if (callback && typeof callback == 'function') {
            callback();
        }
    };

    // submit comment
    this.submitComment = function(comment_content,checked,parentid,callback){

        if (checked == null || checked===true) {
            log('Checking comment content');
            self.checkCommentContent(comment_content, function(){
                self.submitComment(comment_content,false,parentid);
            });
            return;
        }
        
        page.socialplugin.getUserInfo(function(user){            
            if(user==null) {
                log('User not login yet, asking for login ')
                page.socialplugin.login(function(info){
                    self.pushComment(
                        {
                            'userid': info.id,
                            'username':info.name,
                            'useremail':info.email,
                            'useravatar':info.avatar,
                            'comment_content':comment_content
                        }, function(result){
                            if(callback && typeof callback == 'function') {
                                callback(result);
                            }
                        },parentid
                    );
                });
            }
            else {
                log('User login! Now push comment');
                self.pushComment(
                    {
                        'userid': user.id,
                        'username':user.name,
                        'useremail':user.email,
                        'useravatar':user.avatar,
                        'comment_content':comment_content
                    }, function(result){
                        if(callback && typeof callback == 'function') {
                            callback(result);
                        }
                    }, parentid
                );
            }
        });
    };

    // push comment to CMS
    this.pushComment = function(comment, callback, replyto) {
        $comment.find('.form').hide();

        // first fix comment content
        var commentContent = fixContent(comment.comment_content);
        commentContent = fixCommonErrors(commentContent);
        commentContent = capitalizeSentence(commentContent);

        var commentData = {
            'userid':comment.userid,
            'displayname' : comment.username,
            'email' : comment.useremail,
            'comment' : commentContent,
            'avatar':comment.useravatar
        };

        if(replyto) {
            commentData.parentid = replyto;
        }

        // then send comment to server
        $.ajax({
            type : 'POST',
            url : 'http://news.zing.vn/api/comment.aspx?action=post&id='+articleid,
            cache : false,
            data : commentData
        }).fail(function(jqXHR, status, error) {
            log("Network error: "+status);
            $comment.find('.form').show();
            page.showDialog(
                'Thông báo',
                '<p>Có lỗi xảy ra khi gửi bình luận của bạn. Bạn có thể thử lại sau vài phút.</p>'
            );
            if (callback && typeof callback == 'function') {
                callback(false);
            }
        }).done(function(data,status,jqXHR){
            // push comment to cms fail
            if (data.error==1) {
                log('Comment post to CMS fail');
                $comment.find('.form').show();
                page.showDialog(
                    'Thông báo',
                    '<p>Có lỗi xảy ra khi gửi bình luận của bạn. Bạn có thể thử lại sau vài phút.</p>'
                );
                if (callback && typeof callback == 'function') {
                    callback(false);
                }
            }
            // push comment to cms succeed
            else {
                log('Comment post to CMS successfully');
                if(typeof cate_path != 'undefined') {
                    ga('send','event','Article','Comment',cate_path,commentContent.length);
                }
                // if already login to fb, attempt to share
                if(page.socialplugin.isFBLogin && replyto==null) {
                    log('Prepare to share on Facebook...');
                    var $share = $comment.find('.sharefb input');
                    if ($share.length==0) {
                        log('Ask user if he want to share?');
                        page.showDialog(
                            'Chia sẻ bình luận',
                            '<p>Bình luận của bạn đã được gửi thành công! Bạn có muốn chia sẻ suy nghĩ của bạn về bài viết này trên Facebook cùng bạn bè?</p>',
                            {
                                submit: {
                                    text: 'Chia sẻ Facebook',
                                    action: function(){
                                        page.closeDialog();
                                        page.socialplugin.comment(comment.comment_content,$comment.attr('url'));
                                        page.socialplugin.showFanpagePopup();
                                    }
                                },
                                cancel: {
                                    text:'Bỏ qua',
                                    action:function(){
                                        page.closeDialog();
                                        page.socialplugin.showFanpagePopup();
                                    }
                                }
                            }
                        );
                    } else {
                        if($share.is(':checked')) {
                            log('User choose to share!');
                            page.socialplugin.comment(comment.comment_content,$comment.attr('url'));
                        } else {
                            log('User chose not to share comment. Cancel!');
                        }
                        page.showDialog(
                            'Bình luận đã được gửi',
                            '<p>Bình luận của bạn đã được gửi thành công và đang chờ duyệt trước khi hiển thị trên trang.</p>',
                            {
                                cancel: {
                                    text:'Đồng ý', 
                                    action: function(){
                                        page.closeDialog();
                                        page.socialplugin.showFanpagePopup();
                                    }
                                }
                            }
                        );
                    }
                } else {
                    page.showDialog(
                        'Bình luận đã được gửi',
                        '<p>Bình luận của bạn đã được gửi thành công và đang chờ duyệt trước khi hiển thị trên trang.</p>'
                    );
                }

                if (callback && typeof callback == 'function') {
                    callback(true);
                }
            }

        });
    };

    // setup comment box
    var init = function(){
        log('Setting up comment for article#'+articleid);
        //setup
        $comment.attr('id','comment-'+articleid).addClass('commentbox').attr('url','http://news.zing.vn/zing-post'+articleid+'.html').html('');
        $comment.html('<header><h1>Bình luận</h1></header>');
        $comment.append(
            '<div class="form">'
            +'<p class="content"><label>Nội dung</label>'
            +'<textarea></textarea></p>'
            +'<p class="note"><span class="length">tối thiểu 10 chữ</span> <span class="vietnamese">tiếng Việt có dấu</span> <span class="link">không chứa liên kết</span> </p>'
            +'<a href="#" class="btnSubmit disabled">Gửi bình luận</a>'
            +'</div>'            
            +'<ul class="comments"></ul>'
            +'<a href="#" nextpage="1" style="display:none;" class="btnMore">Xem thêm</a>'
        );
        if(DEVICE.platform=='android') {
            $comment.find('textarea').before('<a target="_blank" href="market://details?id=com.vng.inputmethod.labankey" class="btnLabanKey">Cài LabanKey gõ tiếng Việt nhanh hơn</a>')
        }

        $commentField = $comment.find('.form textarea');
        $notes = $comment.find('.note span');
        $btnSubmit = $comment.find('a.btnSubmit');
        $commentList = $comment.find('ul.comments');
        $btnMore = $comment.find('> .btnMore');

        // setup submitting event
        $btnSubmit.on('click',function(e){
            e.preventDefault();
            self.submitComment($commentField.val(),true);
        });

        // user click to see more comments
        $btnMore.on('click',function(e){
            e.preventDefault();
            var orderbytime = ($comment.attr('orderbytime')==1);
            self.updateComment(parseInt($(this).attr('nextpage')),orderbytime);     
        });

        // setup event tracking on textarea
        $commentField.on('input propertychange',function(){
            clearTimeout(checktimer);
            checktimer = setTimeout(function(){
                var comment_content = $commentField.val();
                log('Checking comment content');
                if(comment_content.trim()==''){
                    $notes.removeClass('ok').removeClass('fail');
                    $btnSubmit.addClass('disabled');
                    return;
                }
                var words = comment_content.split(' ');
                if(words.length < 10) {
                    $comment.find('.length').addClass('fail').removeClass('ok');
                } else {
                    $comment.find('.length').addClass('ok').removeClass('fail');
                    $btnSubmit.removeClass('disabled');
                }

                if (words.length > 1) {
                    if(!isVietnamese(comment_content)){
                        $comment.find('.vietnamese').addClass('fail').removeClass('ok');
                    } else {
                        $comment.find('.vietnamese').addClass('ok').removeClass('fail');
                    }

                    if(comment_content.match(/https*:|www\.\S+/i)!=null) {
                        $comment.find('.link').addClass('fail').removeClass('ok');
                    } else {
                        $comment.find('.link').addClass('ok').removeClass('fail');
                    }
                }

            },200);
        });

        // update user info
        page.socialplugin.getUserInfo(function(user){
            if(user==null) return;
            $comment.find('.content label').html(
                '<img src="'+user.avatar+'" width="40" height="40" class="avatar" />'
                +'<strong>'+user.name+'</strong> (<a href="javascript:page.socialplugin.logout();" title="Thoát">Thoát</a>)'
            );
            if($comment.find('.sharefb').length==0) {
                $btnSubmit.after('<label class="sharefb"><input type="checkbox" value="1" checked>Chia sẻ Facebook</label>');
            }

        });

        // update comment list
        var orderbytime = ($comment.attr('orderbytime')==1);
        self.updateComment(1,orderbytime);        

        $comment.show();
    };

    init();
}

/**
 * Video Plugin
 */
function VideoPlayer() {
    var self = this,
        frameWidth = $('#video .player').width(),
        maxHeight = Math.round($(document).height()*0.6),
        playerHeight = Math.round(frameWidth*9/16),
        coverAnimations,
        IS_SINGLE_PLAYER = ($('#video.singleplayer').length > 0);

    if (IS_SINGLE_PLAYER) {
        playerHeight = $(document).height();
    } else if (playerHeight > maxHeight) {
        playerHeight = maxHeight;
        log('Exceed max height');
    }


    this.init = function(){

        // Setup preview video link
        if (window.location.hash.indexOf('next_video') >= 0) {
            $('#video_detail .player').append('<a href="javascript:Player.goBack();" class="btnPrev">Trước</a>');
        }

        // Setup next video link
        var $nextVideo = $('#video_detail .btnNext');
        if ($nextVideo.length > 0) {
            $nextVideo.attr('href', $nextVideo.attr('href') + '#next_video');
        };

        // calculate video duration
        var $timedurations = $('article.video .duration');
        var secs;
        for (var i = 0, j = $timedurations.length; i < j; i++) {
            secs = parseInt($timedurations.eq(i).text());
            if (secs>0) {
                var hr = Math.floor(secs / 3600);
                var min = Math.floor((secs - (hr * 3600))/60);
                var sec = secs - (hr * 3600) - (min * 60);

                if (hr==0) hr = ""; else hr += ":";
                if (min==0) min = ""; else min += ":";
                $timedurations.eq(i).text( hr + min + sec);
            }
        };

        // Setup gif display mechanism
        var $gifs = $('.cover[style*="_gif.jpg"]');
        $gifs.parents('article').addClass('animated');
        $gifs.mouseenter(function(){
            var $self = $(this);
            $self.append('<div id="circleG"><div id="circleG_1" class="circleG"></div><div id="circleG_2" class="circleG"></div><div id="circleG_3" class="circleG"></div></div>');

            // save the origin version
            var static_bg = $self.attr('data-static');
            if (!static_bg) {
                static_bg = $self.css('background-image').replace(/url\(|\)/g,'');
                $self.attr('data-static',static_bg);
            }
            // get the animation version of cover
            var animate_bg = $self.attr('data-gif');
            if (!animate_bg) {
                animate_bg = static_bg.replace('_gif.jpg','.gif');
                $self.attr('data-gif',animate_bg);
            }
            // load the animation image
            var animation = $('<img>',{src:animate_bg,'class':'preloading'}).css({'width':'0px', 'height':'0px'}).ensureLoad(function(){
                //$(self).css('background-image', 'url('+animate_bg+')');
                $self.append('<span class="animategif" style="background-image:url('+animate_bg+')"></span>');
                setTimeout(function(){
                    $('#circleG').remove();
                },500);
            });
            $('body').append(animation);
        }).mouseleave(function(){
            $('img.preloading').remove();
            //$(this).css('background-image','url('+$(this).attr('data-static')+')');
            $(this).find('.animategif').remove();
        });

        return self;
    };

    this.goBack = function(){
        if (document.referrer!="") {
            window.location.href = document.referrer;
        } else {
            history.go(-1);

            setTimeout(function(){
                self.goBack();
            },500);
        }
    };

    this.setupVideo = function() {
        //log('Setting up video page');
        var videoUrl = null;
        var $videos = [],$video;

        // get the video URL
        var $player = $('#video_detail .player > iframe');

        if($player.length>0 && ($player.attr('src')!=null)) {
            if($player.attr('src').search('youtube.com')>=0 && $('.pr_article').length<0) {
                var v = 'http:'+$player.attr('src').replace(/\?.*/ig,'');
                $player.attr('src','http://tv.zing.vn/cms-embed?url='+v+'&cp_id=1327&key='+k('ztv@ZTV_123@z1327'+v)+'&autoplay=true&embed_type=cms&default_format=f720');
            }
            $player.css({'width':'100%','height':playerHeight+'px','display':'block'}).show();
            return;
        }


        $videos = $('#content .content iframe[src*="youtube.com"],#content .content iframe[src*="tv.zing.vn"],#content .content iframe[src*="mp3.zing.vn"]');
        if ($videos.length > 0) {
            $video = $videos.eq(0);
            videoUrl = $video.attr('src');
        }

        if (videoUrl == null) {
            return;
        }

        if (videoUrl.indexOf('tv.zing.vn') >= 0 || videoUrl.indexOf('mp3.zing.vn') >= 0) {

            var videoid = videoUrl.match(/\/([^.^/]*)(\.html)*$/i)[1];
            if (videoUrl.indexOf('autostart=false') > -1) {
                videoUrl = videoUrl.replace('autostart=false', 'autostart=true');
            } else {
                videoUrl += ((videoUrl.indexOf('?') === -1) ? '?' : '&') + 'autostart=true';
            }
            if ($player.length > 0) {
                $player.attr('src',videoUrl).css({'width':'100%','height':playerHeight+'px','display':'block'});
            } else {
                $('#video_detail .player').append($video);
                $video.attr('src', videoUrl);
                $video.css({'height':(playerHeight)+'px'} ).show();

            }
        } else if (videoUrl.indexOf('youtube.com') >= 0) {
            videoUrl = videoUrl.replace(/\?.*/g,''); // clear all parameters
            videoUrl += '?autoplay=1'; // set autoplay
            if (!IS_SINGLE_PLAYER) videoUrl += '&vq=hd720'; // if not embed mode, then select 720 quality

            if (DEVICE.type == "desktop") {
                $('#video_detail .player').append('<video id="youtubeplayer" width="'+frameWidth+'" height="'+playerHeight+'"><source src="'+videoUrl+'" type="video/youtube" ></video>').show();
                $('#youtubeplayer').mediaelementplayer({
                    iPhoneUseNativeControls: true,
                    AndroidUseNativeControls: true,
                    plugins: ['flash','silverlight'],
                    success: function(mediaElement, domObject) {
                        log('Done setting up player, now play');
                        mediaElement.addEventListener('canplay', function() {
                            mediaElement.play(); // Player is ready
                        }, false);

                    }

                });
            } else {
                $('#video_detail .player').append($video);
                $video.attr('src',videoUrl);
                $video.css({'height':(playerHeight)+'px'} ).show();
            }

           /*
            $('#video_detail .player').append($video);
            $video.attr('src',videoUrl);
            $video.css({'height':(playerHeight)+'px'} ).show();
            */
        }

        return false;
    };

}
